<template>
  <div class="register-view-container">
    <div class="background-shapes">
      <div class="shape circle-1"></div>
      <div class="shape circle-2"></div>
    </div>
    
    <div class="register-form-container">
      <div class="form-header">
        <h2>创建新账户</h2>
        <p>加入饱了么平台，开启全新体验</p>
      </div>
      
      <form @submit.prevent="register">
        <div class="input-row">

          <div class="input-group">
            <i class="fas fa-user"></i>
            <input 
              type="text" 
              v-model="registerData.name" 
              placeholder="昵称" 
              required
              :disabled="loading"
            >
          </div>

          <div class="input-group">
            <i class="fas fa-user"></i>
            <input 
              type="text" 
              v-model="registerData.account" 
              placeholder="账户名" 
              required
              :disabled="loading"
            >
          </div>
          
          <div class="input-group">
            <i class="fas fa-envelope"></i>
            <input 
              type="email" 
              v-model="registerData.bindEmail" 
              placeholder="邮箱" 
              required
              :disabled="loading"
            >
          </div>
        </div>
        
        <div class="input-row">
          <div class="input-group">
            <i class="fas fa-lock"></i>
            <input 
              :type="showPassword ? 'text' : 'password'" 
              v-model="registerData.password" 
              placeholder="密码" 
              required
              :disabled="loading"
            >
            <i 
              :class="showPassword ? 'fas fa-eye-slash' : 'fas fa-eye'" 
              @click="togglePasswordVisibility"
              class="password-toggle"
            ></i>
          </div>
          
          <div class="input-group">
            <i class="fas fa-lock"></i>
            <input 
              :type="showPassword ? 'text' : 'password'" 
              v-model="registerData.confirmPassword" 
              placeholder="确认密码" 
              required
              :disabled="loading"
            >
            <i 
              :class="showPassword ? 'fas fa-eye-slash' : 'fas fa-eye'" 
              @click="togglePasswordVisibility"
              class="password-toggle"
            ></i>
          </div>
        </div>
        
        <div class="input-group">
          <i class="fas fa-phone"></i>
          <input 
            type="tel" 
            v-model="registerData.bindPhone" 
            placeholder="手机号码" 
            required
            :disabled="loading"
          >
        </div>
        
        <div class="terms-agree">
          <label>
            <input type="checkbox" v-model="agreeTerms" :disabled="loading"> 我同意 <a href="#">服务条款</a> 和 <a href="#">隐私政策</a>
          </label>
        </div>
        
        <button type="submit" class="register-btn" :disabled="loading">
          <span v-if="loading" class="loading-spinner"></span>
          {{ loading ? '注册中...' : '注册' }}
        </button>
        
        <p class="login-link">
          已有账户? <a href="#" @click.prevent="navigateToLogin">立即登录</a>
        </p>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { 
  insert,
  type User
} from '@/http/User';
import { insertShop, type Shop } from '@/http/Shop';
import { useUserIdStore } from '@/stores/UserId';
import { message } from '@/utils/message';

const router = useRouter();
const userIdStore = useUserIdStore();

// 响应式数据
const registerData = ref({
  name: '',
  account: '',
  bindEmail: '',
  password: '',
  confirmPassword: '',
  bindPhone: ''
});

const loading = ref(false);
const agreeTerms = ref(false);
const showPassword = ref(false);

// 页面加载时检查登录状态
onMounted(() => {
  userIdStore.restoreFromStorage();
  
  // 如果已经登录，直接跳转到用户页面
  if (userIdStore.isAuthenticated) {
    message.info('您已经登录，正在跳转...');
    router.push('/user');
  }
});

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

// 表单验证
const validateForm = (): boolean => {
  if (!registerData.value.name.trim()) {
    message.warning('请输入昵称');
    return false;
  }
  
  if (!registerData.value.account.trim()) {
    message.warning('请输入账户名');
    return false;
  }
  
  if (registerData.value.account.length < 3) {
    message.warning('账户名至少需要3个字符');
    return false;
  }
  
  if (!registerData.value.bindEmail.trim()) {
    message.warning('请输入邮箱');
    return false;
  }
  
  // 简单的邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(registerData.value.bindEmail)) {
    message.warning('请输入有效的邮箱地址');
    return false;
  }
  
  if (!registerData.value.password.trim()) {
    message.warning('请输入密码');
    return false;
  }
  
  if (registerData.value.password.length < 6) {
    message.warning('密码至少需要6个字符');
    return false;
  }
  
  if (registerData.value.password !== registerData.value.confirmPassword) {
    message.warning('两次输入的密码不一致');
    return false;
  }
  
  if (!registerData.value.bindPhone.trim()) {
    message.warning('请输入手机号码');
    return false;
  }
  
  // 简单的手机号格式验证
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(registerData.value.bindPhone)) {
    message.warning('请输入有效的手机号码');
    return false;
  }
  
  if (!agreeTerms.value) {
    message.warning('请同意服务条款和隐私政策');
    return false;
  }
  
  return true;
};

// 注册处理函数
const register = async () => {
  if (!validateForm()) {
    return;
  }
  
  loading.value = true;
  
  try {
    // 创建用户对象
    const newUser: User = {
      id: null,
      createTime: null,
      updateTime: null,
      account: registerData.value.account,
      name: registerData.value.name,
      password: registerData.value.password,
      bindEmail: registerData.value.bindEmail,
      bindPhone: registerData.value.bindPhone,
      role: 'b', // 默认注册为商家用户
      avatar: null
    };
    
    console.log('🚀 开始注册用户:', newUser);
    
    // 调用注册接口
    const userResponse = await insert(newUser);
    
    if (userResponse.data && userResponse.data.id) {
      console.log('✅ 用户注册成功，ID:', userResponse.data.id);
      
      // 保存用户信息到状态管理
      userIdStore.login(userResponse.data, undefined, 'RegisterAutoLogin');
      
      // 如果是商家用户，自动创建店铺
      if (newUser.role === 'b') {
        try {
          const newShop: Shop = {
            id: null,
            createTime: null,
            updateTime: null,
            relaUserId: userResponse.data.id,
            name: `${registerData.value.name}的店铺`,
            description: '欢迎来到我的店铺',
            logoAddress: null,
            address: null,
            positionX: null,
            positionY: null,
            phone: registerData.value.bindPhone,
            startTime: '09:00:00',
            endTime: '22:00:00',
            minOrderAmount: 2000, // 20元起送
            deliveryFee: 500, // 5元配送费
            avRating: null,
            avAmount: null,
            monthlyOrderCount: null,
            image: null
          };
          
          console.log('🏪 开始创建店铺:', newShop);
          
          const shopResponse = await insertShop(newShop);
          console.log('✅ 店铺创建成功:', shopResponse.data);
          
        } catch (shopError: any) {
          console.error('❌ 店铺创建失败:', shopError);
          // 店铺创建失败不影响注册成功
          message.warning('用户注册成功，但店铺创建失败，请稍后手动创建');
        }
      }
      
      message.success('注册成功！正在跳转...');
      
      // 延迟跳转，让用户看到成功消息
      setTimeout(() => {
        router.push('/user');
      }, 1500);
      
    } else {
      message.error('注册失败，请重试');
    }
    
  } catch (error: any) {
    console.error('❌ 注册失败:', error);
    
    if (error.message) {
      message.error(error.message);
    } else if (error.response?.status === 400) {
      message.error('注册信息有误，请检查后重试');
    } else if (error.response?.status === 409) {
      message.error('账户名或邮箱已存在，请更换后重试');
    } else {
      message.error('注册失败，请检查网络连接后重试');
    }
  } finally {
    loading.value = false;
  }
};

// 导航到登录页面
const navigateToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.register-view-container {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.background-shapes {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.shape {
  position: absolute;
  border-radius: 50%;
  opacity: 0.1;
}

.circle-1 {
  width: 400px;
  height: 400px;
  background: linear-gradient(45deg, #a1c4fd, #c2e9fb);
  top: -200px;
  right: -150px;
}

.circle-2 {
  width: 300px;
  height: 300px;
  background: linear-gradient(45deg, #d4fc79, #96e6a1);
  bottom: -150px;
  left: -100px;
}

.register-form-container {
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 40px;
  width: 100%;
  max-width: 550px;
  z-index: 1;
}

.form-header {
  text-align: center;
  margin-bottom: 30px;
}

.form-header h2 {
  font-size: 2rem;
  color: #2c3e50;
  margin-bottom: 10px;
}

.form-header p {
  color: #7f8c8d;
  font-size: 1.1rem;
}

.input-row {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.input-row .input-group {
  flex: 1;
}

.input-group {
  position: relative;
  margin-bottom: 20px;
}

.input-group i {
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);
  color: #7f8c8d;
  font-size: 18px;
}

.input-group .fa-eye {
  left: auto;
  right: 15px;
  cursor: pointer;
}

.input-group input {
  width: 100%;
  padding: 15px 15px 15px 45px;
  border: 1px solid #e1e5eb;
  border-radius: 10px;
  font-size: 1rem;
  transition: all 0.3s ease;
}

.input-group input:focus {
  border-color: #3498db;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
  outline: none;
}

.terms-agree {
  margin: 25px 0;
  font-size: 0.9rem;
  color: #7f8c8d;
}

.terms-agree label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.terms-agree input {
  margin-right: 8px;
}

.terms-agree a {
  color: #3498db;
  text-decoration: none;
  font-weight: 500;
}

.terms-agree a:hover {
  text-decoration: underline;
}

.register-btn {
  width: 100%;
  padding: 15px;
  background: linear-gradient(to right, #9b59b6, #e74c3c);
  color: white;
  border: none;
  border-radius: 10px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.register-btn:hover:not(:disabled) {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.register-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 加载动画 */
.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 密码切换按钮 */
.password-toggle {
  left: auto !important;
  right: 15px !important;
  cursor: pointer;
  transition: color 0.3s ease;
}

.password-toggle:hover {
  color: #3498db;
}

/* 禁用状态的输入框 */
.input-group input:disabled {
  background-color: #f8f9fa;
  cursor: not-allowed;
  opacity: 0.7;
}

/* 禁用状态的复选框 */
.terms-agree input:disabled {
  cursor: not-allowed;
  opacity: 0.7;
}

.login-link {
  text-align: center;
  margin-top: 25px;
  color: #7f8c8d;
}

.login-link a {
  color: #3498db;
  text-decoration: none;
  font-weight: 500;
}

.login-link a:hover {
  text-decoration: underline;
}

@media (max-width: 768px) {
  .input-row {
    flex-direction: column;
    gap: 0;
  }
}

@media (max-width: 480px) {
  .register-form-container {
    padding: 30px 20px;
  }
}
</style>